package com.example.agriculture.controller;



import com.example.agriculture.entity.*;
import com.example.agriculture.service.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


//和页面接收
@Controller
public class AdminController {
    @Resource
    private OrderFormService orderFormService;

    @Resource
    private ProductTypeService productTypeService ;

    @Resource
    private UserInforService userInforService ;

    @Resource
    private ProductService productService;

    @Resource
    private ProducerService producerService;



    //清除session语句
    @GetMapping("backLogin")
    public String backLogin(HttpSession session){
        session.invalidate();
        return "BMS/login";
    }
//管理员后台主页
    @GetMapping("/AIndex")
    public ModelAndView AIndex(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("BMS/ManagePages/a_index");
        //种植户总数
        int producerCount = producerService.count();
        modelAndView.addObject("producerCount",producerCount);
        //用户总数
        int UserCount = userInforService.count();
        modelAndView.addObject("UserCount",UserCount);
        //商品总数
        List<Product> total = productService.total();
        int productcount = 0;
        for (Product product : total){
            productcount+=product.getProductTotal();
        }
        modelAndView.addObject("productcount",productcount);
        //商品类型总数
        int productTypeCount = productTypeService.count();
        modelAndView.addObject("productTypeCount",productTypeCount);
        //订单总数
        int oroderCount = orderFormService.count();
        modelAndView.addObject("oroderCount",oroderCount);

        return modelAndView;
    }
//订单
    //管理员查看订单信息
    @GetMapping("/AOrderInfor")
    public ModelAndView AOrderInfor(@RequestParam(defaultValue = "1") Integer page){
        List<OrderForm> orderForms = orderFormService.queryAllByLimit((page-1)*5,5);
        System.out.println("+++++++++++++++++++++++++++++++++++++++++++");
        System.out.println(orderForms);
        int count = orderFormService.count()/5;
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("BMS/ManagePages/a_order_infor");
        modelAndView.addObject("count",count+1);
        modelAndView.addObject("orderForm",orderForms);
        modelAndView.addObject("page",page);
        return modelAndView;
    }
    @PostMapping("/ASelectAOrderInfor")
    public ModelAndView ASelectAOrderInfor(int keyword,@RequestParam(defaultValue = "1") Integer page){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("BMS/ManagePages/a_order_infor");
        List<OrderForm> orderForms = orderFormService.countAllLimit((page-1)*5,5,keyword);
        int count =  orderFormService.countLimit(keyword)/5;
        modelAndView.addObject("count",count+1);
        modelAndView.addObject("orderForm",orderForms);
        modelAndView.addObject("page",page);
        return modelAndView;
    }
    //退款功能
    @GetMapping("AOrderUpdate")
    public ModelAndView AOrderUpdate(@RequestParam(defaultValue = "1") Integer page){
         String state = "等待审核";
         List<OrderForm> orderForms = orderFormService.queryAllByLimit1((page-1)*5,5,state);
        System.out.println(orderForms);
         ModelAndView modelAndView = new ModelAndView();
         modelAndView.setViewName("BMS/ManagePages/a_order_update");
         int count = orderFormService.count1()/5;
         modelAndView.addObject("count",count+1);
         modelAndView.addObject("orderForm",orderForms);
         modelAndView.addObject("page",page);
         return modelAndView;
    }
    @PostMapping("agree")
    @ResponseBody
    public Map<String, Object> agree(String agree,Integer userId,Integer orderId,Integer count,Float princeTotal,Integer producerId,Integer productId){
        Map<String,Object>map = new HashMap<>();
        System.out.println(agree);
        Producer producer = producerService.queryById(producerId);
        Float producerMoney = (Float) producer.getProducerMoney();
        if (agree.equals("同意")){
            if (producerMoney>=princeTotal) {
                map.put("res", "1");
                map.put("msg", "退款成功");
                //更新种植户的钱
                producerMoney = producerMoney - princeTotal;
                Producer producer1 = new Producer();
                producer1.setProducerId(producerId);
                producer1.setProducerMoney(producerMoney);
                producerService.update(producer1);
                //更新用户的钱
                UserInfor userInfor = userInforService.queryById(userId);
                Float userMoney = (Float) userInfor.getUserMoney();
                userMoney = userMoney + princeTotal;
                UserInfor userInfor1 = new UserInfor();
                userInfor1.setUserId(userInfor.getUserId());
                userInfor1.setUserMoney(userMoney);
                userInforService.update(userInfor1);
                //商品数量的增加
                Product product = productService.queryById(productId);
                int productCount = product.getProductTotal();
                productCount = productCount + count;
                Product product1 = new Product();
                product1.setProductId(productId);
                product1.setProductTotal(productCount);
                productService.update(product1);
                //更新订单表
                OrderForm orderForm = new OrderForm();
                orderForm.setOrderstate("已退款");
                orderForm.setOrderId(orderId);
                orderForm.setAgree(agree);
                orderFormService.update(orderForm);
                return map;
            }
        }else if (agree.equals("拒绝")){
            OrderForm orderForm = new OrderForm();
            orderForm.setOrderstate("退款失败");
            orderForm.setOrderId(orderId);
            orderForm.setAgree(agree);
            orderFormService.update(orderForm);
            map.put("msg","已拒绝用户请求");
            map.put("res",0);
            return map;
        }
        map.put("msg","退款失败，请确认是否输入正确的字段");
        map.put("res",0);
        return map;
    }
//种植商
//管理员新增种植商
@GetMapping("/AProducerAdd")
public String AProducerAdd(){
    return "BMS/ManagePages/a_producer_add";
}
    @PostMapping("/AProducerAddPost")
    public ModelAndView  AProducerAddPost(Producer producer){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:/AProducerInfor");
        int count = producerService.queryAllCount(producer.getProducerNumber());
        if(count<1){
            producerService.insert(producer);
            return modelAndView;
        }
        return modelAndView;
    }
    //管理员查看种植商信息
    @GetMapping("/AProducerInfor")
    public ModelAndView AProducerInfor(@RequestParam(defaultValue = "1") Integer page){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("BMS/ManagePages/a_producer_infor");
        List<Producer> producers = producerService.queryAllByLimit((page-1)*5,5);
        int count = producerService.count()/5;
        modelAndView.addObject("count",count+1);
        modelAndView.addObject("producerinfor",producers);
        modelAndView.addObject("page",page);
        return modelAndView;
    }
    //管理员搜索种植商信息
    @PostMapping("ASelectProducerInfor")
    public ModelAndView ASelectProducerInfor(String keyword,@RequestParam(defaultValue = "1") Integer page){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("BMS/ManagePages/a_producer_infor");
        List<Producer> producer = producerService.queryAllLimit((page-1)*5,5,keyword);
        System.out.println(producer);
        int count =  producerService.countLimit(keyword)/5;
        modelAndView.addObject("count",count+1);
        modelAndView.addObject("producerinfor",producer);
        modelAndView.addObject("page",page);
        return modelAndView;
    }


    //管理员更新种植户信息
    @GetMapping("/AUpDateProducer")
    public ModelAndView AUpDateProducer(Integer id){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("BMS/ManagePages/a_producer_update");
        Producer producer = producerService.queryById(id);
        modelAndView.addObject("updateproducer",producer);
        return modelAndView;
    }
    @PostMapping("/AUpDateProducerMain")
    @ResponseBody
    public ModelAndView AUpDateProducerMain(Producer id){
        producerService.update(id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:/AProducerInfor");
        return modelAndView;

    }
    //管理员删除种植户
    @GetMapping("/delProducer")
    @ResponseBody
    public Map<String, Object> Del(Integer id){
        boolean b = producerService.deleteById(id);
        Map<String,Object>map = new HashMap<>();
        if (b){
            map.put("res","ok");
            map.put("msg","删除成功");
            return map;
        }
        map.put("res","false");
        map.put("msg","删除失败");
        return map;
    }


//商品
    //管理员更新商品
    @GetMapping("/AupdatePuduct")
    public ModelAndView AupdatePuduct(Integer id){
        Product product = productService.queryById(id);
        ModelAndView modelAndView = new ModelAndView();
        System.out.println(product);
        modelAndView.setViewName("BMS/ManagePages/a_product_updata");
        modelAndView.addObject("productsinfor",product);
        return modelAndView;
    }
    @PostMapping("PostAupdatePuduct")
        public ModelAndView PostAupdatePuduct(Product id){
        ModelAndView modelAndView = new ModelAndView();
        productService.update(id);
        modelAndView.setViewName("redirect:/AProductInfor");
        return modelAndView;
    }
    //管理员新增商品
    @GetMapping("/AProductAdd")
        public ModelAndView AProductAdd(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("BMS/ManagePages/a_product_add");
        List<Producer>producers = producerService.SelectAllProducer();
        List<ProductType>productTypes = productTypeService.SelectAllProductTpye();
        System.out.println(productTypes);
        modelAndView.addObject("producers",producers);
        modelAndView.addObject("productTypes",productTypes);
        return modelAndView;
    }
    @PostMapping("/AProductAdd_main")
        public String AProductAddMain(Product product) {
        product.setProductCreatTime(String.valueOf(product.getProductCreatTime()));
        product.setProductReleaseTime(String.valueOf(product.getProductReleaseTime()));
        productService.product(product);

        return "redirect:/AProductInfor";

    }
        //图片添加
        @Value("${web.upload-path}")
        String path;
        @PostMapping("/upFile")
        @ResponseBody
        public String getUpFile(MultipartFile file) throws IOException {
            String s = UUID.randomUUID().toString().replaceAll("-","");
            String originalFilename = file.getOriginalFilename();
            String type = originalFilename.substring(originalFilename.lastIndexOf("."));
            System.out.println(originalFilename);
            file.transferTo(new File(path+"\\"+s+type));
            return s+type;
        }
    //管理员删除商品信息
    @GetMapping("/ADelProduct")
    @ResponseBody
        public Map<String, Object> DelProduct(Integer id){
        boolean b = productService.deleteById(id);
        Map<String,Object>map = new HashMap<>();
        if (b){
            map.put("res","ok");
            map.put("msg","删除成功");
            return map;
        }
        map.put("res","false");
        map.put("msg","删除失败");
        return map;
    }
    //管理员查看商品信息
    @GetMapping("/AProductInfor")
    public ModelAndView AProductInfor(@RequestParam(defaultValue = "1") Integer page, HttpSession session){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("BMS/ManagePages/a_product_infor");
        String name=null;
        List<Product> products = productService.queryAllByLimit(name,(page-1)*5,5,null);
        modelAndView.addObject("productsinfor",products);
        int count = productService.count()/5;
        modelAndView.addObject("count",count+1);
        modelAndView.addObject("page",page);
        return modelAndView;
    }
    //管理员搜索商品
    @PostMapping("/ASelectProductInfor")
    public ModelAndView ASelectProductInfor(String productname,@RequestParam(defaultValue = "1") Integer page){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("BMS/ManagePages/a_product_infor");
        List<Product> products = productService.queryAll((page-1)*5,5,productname);
        int count =  productService.countLimit(productname)/5;
        modelAndView.addObject("count",count+1);
        modelAndView.addObject("productsinfor",products);
        modelAndView.addObject("page",page);
        return modelAndView;
    }

//商品类型
    //管理员新增商品类型
    @GetMapping("/AProductTypeAdd")
    public String AProductTypeAdd(){
        return "BMS/ManagePages/a_product_type_add";
    }
    @PostMapping("AProductTypeAddMain")
    public ModelAndView AProductTypeAddMain(ProductType productType){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:/AProductTypeInfor");
        productTypeService.insert(productType);
        return modelAndView;
    }
    //管理员查看商品类型信息
    @GetMapping("/AProductTypeInfor")
    public ModelAndView AProductTypeInfor(@RequestParam(defaultValue = "1") Integer page){
        ModelAndView modelAndView =new ModelAndView();
        modelAndView.setViewName("BMS/ManagePages/a_product_type_infor");
        int count = productTypeService.count()/5;
        List<ProductType> productTypes = productTypeService.queryAllByLimit((page-1)*5,5);
        modelAndView.addObject("productTypeInfor",productTypes);
        modelAndView.addObject("count",count+1);
        modelAndView.addObject("page",page);
        return modelAndView;
    }
    //管理员搜索商品类型信息
    @PostMapping("/ASelectProductTypeInfor")
    public ModelAndView ASelectProductTypeInfor(String typename,@RequestParam(defaultValue = "1") Integer page){
        ModelAndView modelAndView =new ModelAndView();
        modelAndView.setViewName("BMS/ManagePages/a_product_type_infor");
        List<ProductType> productTypes = productTypeService.queryAll((page-1)*5,5,typename);
        int count =  productTypeService.countLimit(typename)/5;
        modelAndView.addObject("count",count+1);
        modelAndView.addObject("productTypeInfor",productTypes);
        modelAndView.addObject("page",page);
        return modelAndView;
    }
    //删除商品类型
    @GetMapping("/ADelProductTypeInfor")
    @ResponseBody
    public Map<String, Object> ADelProductTypeInfor(Integer id){
        boolean b = productTypeService.deleteById(id);
        Map<String,Object>map = new HashMap<>();
        if (b){
            map.put("res","ok");
            map.put("msg","删除成功");
            return map;
        }
        map.put("res","false");
        map.put("msg","删除失败");
        return map;
    }
    //更新商品类型
    @GetMapping("/AUpDataProductTypeInfor")
    public ModelAndView AUpDataProductTypeInfor(Integer id){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("BMS/ManagePages/a_product_type_updata");
        ProductType productType = productTypeService.queryById(id);
        modelAndView.addObject("AUpDataProductTypeInfor",productType);
        return modelAndView;
    }
    @PostMapping("/PostAUpDataProductTypeInfor")
    public ModelAndView PostAUpDataProductTypeInfor(ProductType id){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:/AProductTypeInfor");
        productTypeService.update(id);
        return modelAndView;
    }

//用户
//管理员新增用户
    @GetMapping("/AserAdd")
    public String AUserAdd() {
        return "BMS/ManagePages/a_user_add";
    }
        @PostMapping("/AserAddPost")
        public String AUserAddPost(UserInfor userInfor){
            int count  = userInforService.queryAllCount(userInfor.getUserNumber());
            if (count<1){
                userInforService.insert(userInfor);
                return "redirect:/AserInfor";
            }
            return "redirect:/AserInfor";
        }
    //管理员查看用户信息
    @GetMapping("/AserInfor")
    public ModelAndView AserInfor(@RequestParam(defaultValue = "1") Integer page){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("BMS/ManagePages/a_user_infor");
        List<UserInfor> userInfors = userInforService.queryAllByLimit((page-1)*5,5);
        int count = userInforService.count()/5;
        modelAndView.addObject("userInfors",userInfors);
        modelAndView.addObject("count",count+1);
        modelAndView.addObject("page",page);
        return modelAndView;
    }
    //管理员搜索用户信息
    @PostMapping("ASelectserInfor")
    public ModelAndView ASelectserInfor(String keyword,@RequestParam(defaultValue = "1") Integer page){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("BMS/ManagePages/a_user_infor");
        List<UserInfor> userInfors =userInforService.queryAllLimit((page-1)*5,5,keyword);
        int count =  userInforService.countLimit(keyword)/5;
        modelAndView.addObject("count",count+1);
        modelAndView.addObject("userInfors",userInfors);
        modelAndView.addObject("page",page);
        return modelAndView;
    }
    //管理员删除用户
    @GetMapping("/Aserdel")
    @ResponseBody
    public Map<String, Object> AUserdel(Integer userId){
        boolean b = userInforService.deleteById(userId);
        Map<String,Object>map = new HashMap<>();
        if (b){
            map.put("res","ok");
            map.put("msg","删除成功");
            return map;
        }
        map.put("res","false");
        map.put("msg","删除失败");
        return map;
    }
    //管理员编辑用户信息
    @GetMapping("/Aserupdata")
    public ModelAndView Aserupdata(Integer id){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("BMS/ManagePages/a_user_updata");
        UserInfor userInfor =  userInforService.queryById(id);
        modelAndView.addObject("userInfor",userInfor);
        return modelAndView;
    }
    @PostMapping("/PostAserupdata")
    public ModelAndView PostAserupdata(UserInfor userInfor){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:/AserInfor");
        userInforService.update(userInfor);
//        List<UserInfor> userInfors = userInforService.queryAllByLimit(0,10);
//        modelAndView.addObject("userInfors",userInfors);
        return modelAndView;
    }
}
